import { blogPosts, type BlogPost } from "./blog-posts"

export type { BlogPost }

export function getAllPosts(): BlogPost[] {
  return blogPosts.sort((a, b) => (new Date(a.date) > new Date(b.date) ? -1 : 1))
}

export function getPostBySlug(slug: string): BlogPost | null {
  return blogPosts.find((post) => post.slug === slug) || null
}

export function getFeaturedPosts(count = 3): BlogPost[] {
  const allPosts = getAllPosts()
  return allPosts.slice(0, count)
}

export function getAllTags(): string[] {
  const allTags = blogPosts.flatMap((post) => post.tags)
  return Array.from(new Set(allTags)).sort()
}

export function getPostsByTag(tag: string): BlogPost[] {
  return blogPosts
    .filter((post) => post.tags.includes(tag))
    .sort((a, b) => (new Date(a.date) > new Date(b.date) ? -1 : 1))
}

export function getRelatedPosts(currentSlug: string, count = 3): BlogPost[] {
  const currentPost = getPostBySlug(currentSlug)
  if (!currentPost) return []

  const relatedPosts = blogPosts
    .filter((post) => post.slug !== currentSlug && post.tags.some((tag) => currentPost.tags.includes(tag)))
    .sort((a, b) => {
      const aCommonTags = a.tags.filter((tag) => currentPost.tags.includes(tag)).length
      const bCommonTags = b.tags.filter((tag) => currentPost.tags.includes(tag)).length
      return bCommonTags - aCommonTags
    })

  return relatedPosts.slice(0, count)
}
